//
//  DMInAppVerifyManager.m
//  DMPolymerizeSDK
//
//  Created by YeJary on 2025/4/29.
//

#import "DMInAppVerifyManager.h"
#import "DMInAppPurchaseManager+private.h"
#import "../../Utils/Logger/IMLogUtils.h"
#import "../../Utils/Network/IMNetworkUtils.h"
#import "DMConfigReader.h"
#import "IMAPIConfig.h" // 添加IMAPIConfig导入
#import "IMKeychainUUIDManager.h"
#import "DMThinkingManager.h"

#define kDMPendingOrdersKey @"DMInAppPendingOrders"

static NSString *const kApp_id = @"app_id";
static NSString *const kOriginal_transaction_id = @"original_transaction_id";
static NSString *const kProduct_id = @"product_id";
static NSString *const kUuid = @"uuid";
static NSString *const kEnvType = @"envType";

@interface DMInAppVerifyManager ()

@property (nonatomic, strong) NSMutableArray<NSDictionary *> *pendingOrders;
@property (nonatomic, strong) NSMutableSet *verifiedTransactions;

@end

@implementation DMInAppVerifyManager

+ (instancetype)sharedManager {
    static DMInAppVerifyManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
        [manager loadPendingOrders];
        manager.verifiedTransactions = [NSMutableSet set];
    });
    return manager;
}

#pragma mark - 核心校验逻辑

- (void)verifyTransactionWithTransactionId:(NSString *)transactionId
                                  productId:(NSString *)productId
                                       uuid:(NSString *)uuid
                                   envType:(NSString *)envType{
    if (transactionId.length == 0 || productId.length == 0 || uuid.length == 0) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 参数缺失，无法进行收据验证 - 交易ID: %@", transactionId ?: @"未知"];
        return;
    }

    if ([self.verifiedTransactions containsObject:transactionId]) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 交易 %@ 已验证，跳过重复验证", transactionId];
        return;
    }

    NSDictionary *params = @{
        kApp_id: @"yw0yqjwcunjjc2e9" ?: @"", // 使用DMConfigReader获取SDK App ID
        kOriginal_transaction_id: transactionId,
        kProduct_id: productId,
        kUuid: uuid,
        kEnvType: envType
    };

    [self sendVerifyRequestWithParams:params retryCount:5];
}

- (void)sendVerifyRequestWithParams:(NSDictionary *)params retryCount:(NSInteger)retryCount {
    // 读取只读字段
    NSString *appId = params[kApp_id] ?: @"";
    NSString *uuid = params[kUuid] ?: @"";
    NSString *productId = params[kProduct_id] ?: @"";
    NSString *originalTransactionId = params[kOriginal_transaction_id] ?: @"";
    
    // 复制为可变字典后再做删改
    NSMutableDictionary *body = params ? [params mutableCopy] : [NSMutableDictionary dictionary];
    
    NSString *envType = [body[kEnvType] ?: @"" description];
    [body removeObjectForKey:kEnvType];   // ✅ 现在在可变字典上删除
    
    __weak typeof(self) weakSelf = self;
    
    // 构建完整的URL
    NSString *baseURL = [IMAPIConfig sharedConfig].inAppPurchaseBaseURL;
    NSString *fullURL = [baseURL stringByAppendingString:@"/api/inappios/verifyV2"];
    
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 开始收据验证网络请求，交易ID: %@", originalTransactionId];
    
    // 使用IMNetworkUtils发送真实网络请求
    [IMNetworkUtils postPaymentRequest:fullURL
                            parameters:body
                               success:^(IMNetworkResponse *response) {
        id responseData = response.data;
        NSInteger code = [responseData[@"code"] integerValue];
        switch (code) {
            case 200: {
                [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 收据校验成功，交易ID: %@", originalTransactionId];
                [weakSelf.verifiedTransactions addObject:originalTransactionId];
                
                DMProductType productType = [[DMInAppPurchaseManager shareInAppPurchaseManager] getProductType:productId];
                
                [[DMInAppPurchaseManager shareInAppPurchaseManager] completeTransactionWithTransactionId:originalTransactionId
                                                                                               productId:productId
                                                                                             receiptType:envType];
                
                [weakSelf removePendingOrder:params];
                break;
            }
            case 3001: {
                [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 收据重复，交易ID: %@", originalTransactionId];
                [weakSelf.verifiedTransactions addObject:originalTransactionId];
                
                DMProductType productType = [[DMInAppPurchaseManager shareInAppPurchaseManager] getProductType:productId];
                
                if (productType == DMProductTypeNonConsumable) {
                    [IMLogUtils info:IMLogTagIAP format:@"🔄 非消耗型商品重复订单，尝试恢复购买"];
                    [[DMInAppPurchaseManager shareInAppPurchaseManager] savePurchaseRecord:productId];
                    
                    // 使用 DMAdDelegate 的恢复购买成功回调
                    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didSuccessRestoreInAppPurchase:transactionId:)]) {
                        [self.delegate dmAdManager:nil didSuccessRestoreInAppPurchase:productId transactionId:originalTransactionId];
                    }
                } else {
                    [[DMInAppPurchaseManager shareInAppPurchaseManager] handleDuplicateTransaction:originalTransactionId
                                                                                         productId:productId];
                }
                
                [weakSelf removePendingOrder:params];
                break;
            }
            case 3002:
            default: {
                [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 校验失败，交易ID: %@，错误信息: 服务器 code: %ld", originalTransactionId, (long)code];
                if (retryCount > 0) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [weakSelf sendVerifyRequestWithParams:params retryCount:retryCount - 1];
                    });
                } else {
                    [weakSelf cachePendingOrder:params];
                }
                break;
            }
        }
    } failure:^(IMNetworkResponse *response) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 校验网络失败: %@", response.error.localizedDescription];
        if (retryCount > 0) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf sendVerifyRequestWithParams:params retryCount:retryCount - 1];
            });
        } else {
            [weakSelf cachePendingOrder:params];
        }
    }];
}

#pragma mark - 补单管理

- (void)autoRetryPendingOrders {
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 启动自动补单，总数 = %ld", (long)self.pendingOrders.count];
    if (self.pendingOrders.count == 0) return;

    [self.verifiedTransactions removeAllObjects];

    // 使用快照避免在遍历时因 sendVerifyRequestWithParams: 触发对 pendingOrders 的修改而崩溃
    NSArray *pendingSnapshot = [self.pendingOrders copy];
    for (NSDictionary *order in pendingSnapshot) {
        [self sendVerifyRequestWithParams:order retryCount:5];
    }
}

- (void)cachePendingOrder:(NSDictionary *)order {
    if (!order) return;
    if (![self.pendingOrders containsObject:order]) {
        [self.pendingOrders addObject:order];
        [self savePendingOrders];
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 已缓存未校验订单，总数 = %ld", (long)self.pendingOrders.count];
    }
}

- (BOOL)isPendingOrderTransactionId:(NSString *)transactionId {
    if (transactionId.length == 0) return NO;
    for (NSDictionary *order in self.pendingOrders) {
        NSString *cachedId = order[kOriginal_transaction_id];
        if ([cachedId isEqualToString:transactionId]) {
            return YES;
        }
    }
    return NO;
}

- (void)removePendingOrder:(NSDictionary *)order {
    if (!order) return;
    [self.pendingOrders removeObject:order];
    [self savePendingOrders];
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 已移除重复订单 order = %@", order];
}

- (void)loadPendingOrders {
    NSArray *cached = [[NSUserDefaults standardUserDefaults] objectForKey:kDMPendingOrdersKey];
    self.pendingOrders = cached ? [cached mutableCopy] : [NSMutableArray array];
}

- (void)savePendingOrders {
    [[NSUserDefaults standardUserDefaults] setObject:self.pendingOrders forKey:kDMPendingOrdersKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)clearVerifiedTransactions {
    [self.verifiedTransactions removeAllObjects];
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 已清除所有已验证交易记录"];
}

- (BOOL)isTransactionVerified:(NSString *)transactionId {
    return [self.verifiedTransactions containsObject:transactionId];
}

#pragma mark - 核销接口

- (void)acknowledgeInAppPurchaseWithOriginal_transaction_id:(NSString *)originalTransactionId
                                            successCallback:(DMInAppPurchaseSuccessCallback)successCallback
                                            failureCallback:(DMInAppPurchaseFailureCallback)failureCallback {
    if (originalTransactionId.length == 0) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 核销失败：原始交易ID不能为空"];
        if (failureCallback) {
            NSError *error = [NSError errorWithDomain:@"DMInAppPurchaseError"
                                                code:-1001
                                            userInfo:@{NSLocalizedDescriptionKey: @"原始交易ID不能为空"}];
            failureCallback(error);
        }
        return;
    }
    
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 开始核销订单，交易ID: %@", originalTransactionId];
    
    // 构建核销请求参数
    NSDictionary *params = @{
        kApp_id: @"yw0yqjwcunjjc2e9" ?: @"",
        kOriginal_transaction_id: originalTransactionId
    };
    
    [self sendAcknowledgeRequestWithParams:params
                           successCallback:successCallback
                           failureCallback:failureCallback];
}

- (void)sendAcknowledgeRequestWithParams:(NSDictionary *)params
                         successCallback:(DMInAppPurchaseSuccessCallback)successCallback
                         failureCallback:(DMInAppPurchaseFailureCallback)failureCallback {
    NSString *originalTransactionId = params[kOriginal_transaction_id] ?: @"";
    
    __weak typeof(self) weakSelf = self;
    
    // 构建完整的URL
    NSString *baseURL = [IMAPIConfig sharedConfig].inAppPurchaseBaseURL;
    NSString *fullURL = [baseURL stringByAppendingString:@"/api/inappios/ack"];
    
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 开始核销网络请求，交易ID: %@", originalTransactionId];
    
    // 使用IMNetworkUtils发送真实网络请求
    [IMNetworkUtils postPaymentRequest:fullURL
                            parameters:params
                               success:^(IMNetworkResponse *response) {
        id responseData = response.data;
        
        NSInteger code = [responseData[@"code"] integerValue];
        if (code == 200) {
            [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 订单核销成功，交易ID: %@", originalTransactionId];
            
            // Billing_props_issued 道具核销成功事件打点
            NSDictionary *billingPropsIssuedParams = @{
                @"w_is_success": @YES,
                @"w_purchase_token": originalTransactionId ?: @"",
                @"w_error_code": @"",
                @"w_error_msg": @""
            };
            [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"Billing_props_issued" properties:billingPropsIssuedParams];
            [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: Billing_props_issued - 道具核销成功，交易ID: %@", originalTransactionId];
            
            // 标记为已验证
            [weakSelf.verifiedTransactions addObject:originalTransactionId];
            
            // 从待处理订单中移除
            [weakSelf removePendingOrderByTransactionId:originalTransactionId];
            
            if (successCallback) {
                successCallback(originalTransactionId);
            }
        } else {
            [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 订单核销失败，交易ID: %@, 错误码: %ld", originalTransactionId, (long)code];
            
            // Billing_props_issued 道具核销失败事件打点
            NSString *message = responseData[@"message"] ?: @"核销失败";
            NSDictionary *billingPropsIssuedParams = @{
                @"w_is_success": @NO,
                @"w_purchase_token": originalTransactionId ?: @"",
                @"w_error_code": @(code).stringValue,
                @"w_error_msg": message
            };
            [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"Billing_props_issued" properties:billingPropsIssuedParams];
            [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: Billing_props_issued - 道具核销失败，交易ID: %@, 错误码: %ld", originalTransactionId, (long)code];
            
            if (failureCallback) {
                NSError *error = [NSError errorWithDomain:@"DMInAppPurchaseError"
                                                     code:code
                                                 userInfo:@{NSLocalizedDescriptionKey: message}];
                failureCallback(error);
            }
        }
    } failure:^(IMNetworkResponse *response) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 核销网络请求失败: %@", response.error.localizedDescription];
        
        // Billing_props_issued 道具核销网络请求失败事件打点
        NSDictionary *billingPropsIssuedParams = @{
            @"w_is_success": @NO,
            @"w_purchase_token": originalTransactionId ?: @"",
            @"w_error_code": @(response.error.code).stringValue,
            @"w_error_msg": response.error.localizedDescription ?: @"网络请求失败"
        };
        [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"Billing_props_issued" properties:billingPropsIssuedParams];
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: Billing_props_issued - 道具核销网络请求失败，交易ID: %@", originalTransactionId];
        
        if (failureCallback) {
            failureCallback(response.error);
        }
    }];
}

- (void)removePendingOrderByTransactionId:(NSString *)transactionId {
    if (transactionId.length == 0) return;
    
    NSMutableArray *ordersToRemove = [NSMutableArray array];
    for (NSDictionary *order in self.pendingOrders) {
        NSString *cachedId = order[kOriginal_transaction_id];
        if ([cachedId isEqualToString:transactionId]) {
            [ordersToRemove addObject:order];
        }
    }
    
    for (NSDictionary *order in ordersToRemove) {
        [self.pendingOrders removeObject:order];
    }
    
    if (ordersToRemove.count > 0) {
        [self savePendingOrders];
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 已移除 %ld 个待处理订单", (long)ordersToRemove.count];
    }
}

#pragma mark - 未核销订单查询接口

- (void)fetchUnacknowledgedOrdersWithSuccess:(DMUnacknowledgedOrdersCallback)successCallback
                                     failure:(DMInAppPurchaseFailureCallback)failureCallback {
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 开始查询未核销订单"];
    
    __weak typeof(self) weakSelf = self;
    
    // 构建查询请求参数
    NSDictionary *params = @{
        kApp_id: @"yw0yqjwcunjjc2e9" ?: @"",
        @"uuid": [IMKeychainUUIDManager getOrCreateLoginUUID],
    };
    
    // 构建完整的URL
    NSString *baseURL = [IMAPIConfig sharedConfig].inAppPurchaseBaseURL;
    NSString *fullURL = [baseURL stringByAppendingString:@"/api/inappios/unAckOrder"];
    
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 查询未核销订单"];
    
    // 使用IMNetworkUtils发送真实网络请求
    [IMNetworkUtils postPaymentRequest:fullURL
                            parameters:params
                               success:^(IMNetworkResponse *response) {
        [weakSelf handleFetchUnacknowledgedOrdersResponse:response.data successCallback:successCallback failureCallback:failureCallback];
    } failure:^(IMNetworkResponse *response) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 未核销订单查询网络请求失败: %@", response.error.localizedDescription];
        
        if (failureCallback) {
            failureCallback(response.error);
        }
    }];
}

- (void)handleFetchUnacknowledgedOrdersResponse:(id)responseData
                                successCallback:(DMUnacknowledgedOrdersCallback)successCallback
                                failureCallback:(DMInAppPurchaseFailureCallback)failureCallback {
    NSInteger code = [responseData[@"code"] integerValue];
    if (code == 200) {
        id dataObj = responseData[@"data"];
        NSArray *orders = @[];

        // data 可能是数组或字典（兼容两种返回格式）
        if ([dataObj isKindOfClass:[NSArray class]]) {
            orders = (NSArray *)dataObj;
            [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 未核销查询返回数组格式，直接使用 data 作为订单列表"];
        } else if ([dataObj isKindOfClass:[NSDictionary class]]) {
            id ordersObj = ((NSDictionary *)dataObj)[@"orders"];
            if ([ordersObj isKindOfClass:[NSArray class]]) {
                orders = (NSArray *)ordersObj;
            } else if (ordersObj && ![ordersObj isKindOfClass:[NSNull class]]) {
                // 非数组但存在，做一次尽力而为的兼容
                orders = @[ordersObj];
                [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] orders 字段不是数组，已做兼容包装"];
            }
        } else if (dataObj && ![dataObj isKindOfClass:[NSNull class]]) {
            [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 未核销查询 data 字段类型异常: %@", NSStringFromClass([dataObj class])];
        }

        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 未核销订单查询成功，共 %ld 个订单", (long)orders.count];
        if (successCallback) {
            successCallback(orders ?: @[]);
        }
    } else {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 未核销订单查询失败，错误码: %ld", (long)code];
        if (failureCallback) {
            NSString *message = responseData[@"message"] ?: @"查询失败";
            NSError *error = [NSError errorWithDomain:@"DMInAppPurchaseError"
                                                code:code
                                            userInfo:@{NSLocalizedDescriptionKey: message}];
            failureCallback(error);
        }
    }
}

- (NSArray *)formatPendingOrdersForCallback {
    NSMutableArray *formattedOrders = [NSMutableArray array];
    
    for (NSDictionary *order in self.pendingOrders) {
        NSMutableDictionary *formattedOrder = [NSMutableDictionary dictionary];
        
        // 提取订单信息
        NSString *transactionId = order[kOriginal_transaction_id] ?: @"";
        NSString *productId = order[kProduct_id] ?: @"";
        NSString *appId = order[kApp_id] ?: @"";
        NSString *uuid = order[kUuid] ?: @"";
        NSString *envType = order[kEnvType] ?: @"";
        
        // 格式化为标准格式
        formattedOrder[@"original_transaction_id"] = transactionId;
        formattedOrder[@"product_id"] = productId;
        formattedOrder[@"app_id"] = appId;
        formattedOrder[@"uuid"] = uuid;
        formattedOrder[@"env_type"] = envType;
        formattedOrder[@"status"] = @"pending"; // 待核销状态
        formattedOrder[@"created_time"] = @([[NSDate date] timeIntervalSince1970]); // 模拟创建时间
        
        [formattedOrders addObject:[formattedOrder copy]];
    }
    
    return [formattedOrders copy];
}

#pragma mark - 收据校验接口

- (void)verifyInAppReceiptWithAppId:(NSString *)appId
                        receiptData:(NSData *)receiptData
                    successCallback:(DMInAppPurchaseSuccessCallback)successCallback
                    failureCallback:(DMInAppPurchaseFailureCallback)failureCallback {
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 开始校验内购收据，AppId: %@", appId];
    
    if (!appId || appId.length == 0) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 收据校验失败：AppId不能为空"];
        if (failureCallback) {
            NSError *error = [NSError errorWithDomain:@"DMInAppPurchaseError"
                                                code:-1002
                                            userInfo:@{NSLocalizedDescriptionKey: @"AppId不能为空"}];
            failureCallback(error);
        }
        return;
    }
    
    if (!receiptData || receiptData.length == 0) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 收据校验失败：收据数据不能为空"];
        if (failureCallback) {
            NSError *error = [NSError errorWithDomain:@"DMInAppPurchaseError"
                                                code:-1003
                                            userInfo:@{NSLocalizedDescriptionKey: @"收据数据不能为空"}];
            failureCallback(error);
        }
        return;
    }
    
    // 将收据数据转换为Base64字符串
    NSString *receiptString = [receiptData base64EncodedStringWithOptions:0];
    
    if (!receiptString || receiptString.length == 0) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 收据校验失败：收据数据格式错误"];
        if (failureCallback) {
            NSError *error = [NSError errorWithDomain:@"DMInAppPurchaseError"
                                                code:-1004
                                            userInfo:@{NSLocalizedDescriptionKey: @"收据数据格式错误"}];
            failureCallback(error);
        }
        return;
    }
    
    // 构建校验请求参数
    NSDictionary *params = @{
        kApp_id: appId,
        @"receipt_data": receiptString,
        @"device_id": [self generateDeviceId],
        @"timestamp": @([[NSDate date] timeIntervalSince1970])
    };
    
    [self sendReceiptVerifyRequestWithParams:params
                             successCallback:successCallback
                             failureCallback:failureCallback];
}

- (void)sendReceiptVerifyRequestWithParams:(NSDictionary *)params
                           successCallback:(DMInAppPurchaseSuccessCallback)successCallback
                           failureCallback:(DMInAppPurchaseFailureCallback)failureCallback {
    NSString *appId = params[kApp_id] ?: @"";
    NSString *receiptData = params[@"receipt_data"] ?: @"";
    
    __weak typeof(self) weakSelf = self;
    
    // 构建完整的URL
    NSString *baseURL = [IMAPIConfig sharedConfig].inAppPurchaseBaseURL;
    NSString *fullURL = [baseURL stringByAppendingString:@"/api/iap/receipt/verify"];
    
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 开始收据校验网络请求，AppId: %@", appId];
    
    // 使用IMNetworkUtils发送真实网络请求
    [IMNetworkUtils POST:fullURL
              parameters:params
                 success:^(IMNetworkResponse *response) {
        [weakSelf handleReceiptVerifyResponse:response.data
                              successCallback:successCallback
                              failureCallback:failureCallback];
    } failure:^(IMNetworkResponse *response) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 收据校验网络请求失败: %@", response.error.localizedDescription];
        
        if (failureCallback) {
            failureCallback(response.error);
        }
    }];
}

- (void)handleReceiptVerifyResponse:(id)responseData
                    successCallback:(DMInAppPurchaseSuccessCallback)successCallback
                    failureCallback:(DMInAppPurchaseFailureCallback)failureCallback {
    NSInteger code = [responseData[@"code"] integerValue];
    if (code == 200) {
        NSDictionary *data = responseData[@"data"];
        NSString *receiptStatus = data[@"receipt_status"] ?: @"";
        NSString *appId = data[@"app_id"] ?: @"";
        
        if ([receiptStatus isEqualToString:@"valid"]) {
            [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 收据校验成功，AppId: %@", appId];
            
            if (successCallback) {
                successCallback(data);
            }
        } else {
            [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 收据校验失败，收据状态无效: %@", receiptStatus];
            
            if (failureCallback) {
                NSError *error = [NSError errorWithDomain:@"DMInAppPurchaseError"
                                                    code:-1005
                                                userInfo:@{NSLocalizedDescriptionKey: @"收据状态无效"}];
                failureCallback(error);
            }
        }
    } else {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 收据校验失败，错误码: %ld", (long)code];
        
        if (failureCallback) {
            NSString *message = responseData[@"message"] ?: @"收据校验失败";
            NSError *error = [NSError errorWithDomain:@"DMInAppPurchaseError"
                                                code:code
                                            userInfo:@{NSLocalizedDescriptionKey: message}];
            failureCallback(error);
        }
    }
}

- (NSString *)generateDeviceId {
    // 生成设备唯一标识符
    NSString *deviceId = [[NSUserDefaults standardUserDefaults] stringForKey:@"DMDeviceId"];
    if (!deviceId) {
        deviceId = [[NSUUID UUID] UUIDString];
        [[NSUserDefaults standardUserDefaults] setObject:deviceId forKey:@"DMDeviceId"];
        [[NSUserDefaults standardUserDefaults] synchronize];   // iOS 12 以前可选，13+ 不必手动
    }
    return deviceId;
}

@end
